<template>
    <div>
        <!-- 查询条件开始 -->
        <el-form ref="queryForm" :model="search" :inline="true" label-width="68px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input
                        v-model="search.roleName"
                        placeholder="请输入角色名称"
                        clearable
                        size="small"
                        style="width:240px"/>
            </el-form-item>
            <el-form-item label="权限字符" prop="roleCode">
                <el-input
                        v-model="search.roleCode"
                        placeholder="请输入权限字符"
                        clearable
                        size="small"
                        style="width:240px"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                        v-model="search.status"
                        placeholder="可用状态"
                        clearable
                        size="small"
                        style="width:240px">
                    <el-option
                            v-for="dict in statusOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"/>
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                        v-model="search.dateRange"
                        size="small"
                        style="width:240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholde="开始日期"
                        end-placeholde="结束日期"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="searchdata">搜索</el-button>
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="clearsearch">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 查询条件结束 -->
        <!-- 表格工具按钮开始 -->
        <el-row :gutter="10" style="margin-bottom: 8px;">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="addRole">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="bachRole">批量删除</el-button>
            </el-col>
        </el-row>
        <!-- 表格工具按钮结束 -->

        <!-- 添加修改弹出层开始 -->
        <el-dialog
                :title="title"
                :visible.sync="dialogVisible"
                width="500px"
                center
                append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" placeholder="请输入角色名称" clearable size="small" />
                </el-form-item>
                <el-form-item label="权限编码" prop="roleCode">
                    <el-input v-model="form.roleCode" placeholder="请输入权限字符" clearable size="small" />
                </el-form-item>
                <el-form-item label="显示顺序" prop="roleSort">
                    <el-input-number v-model="form.roleSort" clearable size="small" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio
                                v-for="dict in statusOptions"
                                :key="dict.dictValue"
                                :label="dict.dictValue"
                                :value="dict.dictValue">{{ dict.dictLabel }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入字典备注" clearable size="small" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
        </el-dialog>
        <!-- 添加修改弹出层结束 -->
        <!-- 数据表格开始 -->
        <el-table  border :data="tableData"
                   ref="multipleTable"
                   tooltip-effect="dark"
                   style="width: 100%"
                   @selection-change="handleSelectionChange">>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="角色ID" align="center" prop="roleId" />
            <el-table-column label="角色名称" align="center" prop="roleName" />
            <el-table-column label="权限编码" align="center" prop="roleCode" />
            <el-table-column label="显示顺序" align="center" prop="roleSort" />
            <el-table-column label="状态" prop="status" align="center" :formatter="statusformat" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="170px"/>
            <el-table-column label="操作" align="center" width="280">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                    <el-button type="text" icon="el-icon-thumb" size="mini"  @click="permanage(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 数据表格结束 -->

        <!-- 分配权限和菜单弹出层开始 -->
        <el-dialog
                :visible.sync="selectMenuOpen"
                width="400px"
                center
                append-to-body>
            <el-tree
                    ref="menu"
                    :data="menuOptions"
                    show-checkbox
                    node-key="menuId"
                    highlight-current
                    empty-text="加载中，请稍后"
                    :props="{id:'menuId',children:'children',label:'menuName'}"/>
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelectMenuSubmit" >确 定</el-button>
        <el-button >取 消</el-button>
      </span>
        </el-dialog>
        <!-- 分配权限和菜单弹出层结束 -->

<!--  分页-->
        <el-pagination
                v-show="page.total>0"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.current"
                :page-sizes="[4, 5, 6]"
                :page-size="page.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total">
        </el-pagination>
    </div>
</template>
<style>
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
</style>
<script>
    export default {
        data() {
            return {
                //状态字典
                statusOptions:[],
                //删除多选框
                multipleSelection: [],
                //条件查询
                search:{},
                //分页
                page:{
                    current:1,
                    size:4,
                    total:10
                },
                //表单数据
                tableData: [],
                //开启对话框 添加role
                dialogVisible:false,
                //对话框标题
                title:'',
                //添加修改表单数据
                form:{},
                //控制分配权限弹出层的显示和隐藏
                selectMenuOpen:false,
                //树形菜单的数据
                menuOptions:[],
                //当前的角色id
                roleId:0,
                //被勾选的菜单id
                checkIds:[],
                // 表单校验
                rules: {
                    roleName: [
                        { required: true, message: '角色名称不能为空', trigger: 'blur' }
                    ],
                    roleCode: [
                        { required: true, message: '权限编码不能为空', trigger: 'blur' }
                    ]
                },
            }
        },
        methods: {

            //获取所有被选中的id
            handleSelectMenuSubmit(){
                let checkAllIds=this.$refs.menu.getCheckedKeys()
                let checkHalfIds=this.$refs.menu.getHalfCheckedKeys()
                let keys=checkAllIds.concat(checkHalfIds);
                this.$axios.post("/system/api/menu/confirmMenu?roleId="+this.roleId+"&menuIds="+keys).then(result=>{
                    this.selectMenuOpen=false;
                    this.$message.success("分配权限成功")
                })
            },
            //加载系统状态
            initStatus() {
                this.$axios.get("system/api/dict/data/findByType/sys_normal_disable").then(r => {
                    this.statusOptions = r.data.t;
                })
            },
            //查询表单数据
            initRoleTable(){
                //分页数据+查询数据
                const newParam=Object.assign(this.search, this.page);
                this.$axios.post("system/api/role/list",newParam).then(r=>{
                    this.tableData=r.data.t.records;
                    this.page.total=r.data.t.total;
                })
            },
            //状态字典解析
            statusformat(row){
                let val=row.status;
                return this.formatDict(this.statusOptions,val)
            },
            //批量删除操作
            bachRole(){
                //传递哪些参数？userId  roleIds
                let roleIds=[];
                this.multipleSelection.forEach(item=>{
                    roleIds.push(item.roleId);
                })
                this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.delete("system/api/role/bachUser/"+roleIds).then(r=>{
                        if (r.data.t){
                            this.$message.success(r.data.msg);
                        }else {
                            this.$message.error("删除失败");
                        }
                        this.page.current=1;
                        this.initRoleTable();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //多选框
            handleSelectionChange(val) {
                this.multipleSelection = val;

            },
            //条件查询、重置数据
            clearsearch(){
                this.search={};
            },
            //条件查询
            searchdata(){
                //查询完成后回到第一页
                this.page.current=1;
                this.initRoleTable();
            },
            //每页显示的条数
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.page.size=val;
                this.initRoleTable();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.page.current=val;
                this.initRoleTable();
            },
            //添加角色 2、提交表单
            handleSubmit() {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.$axios.post("system/api/role/saveOrUpdateRole",this.form).then(r=>{
                            if (r.data.t){
                                this.$message.success(r.data.msg);
                            }else {
                                this.$message.error("操作失败");
                            }
                            this.initRoleTable();
                            this.dialogVisible=false;
                            this.title='';
                            this.form={};
                        })
                    }
                });
            },
            //1、取消添加修改表单
            cancel() {
                this.dialogVisible=false;
            },
            //添加角色 1、开启对话框启用添加表单
            addRole(){
                if (this.$refs.form != undefined) {
                    this.$refs.form.clearValidate();
                }
                this.title="添加角色信息";
                this.dialogVisible=true;
                this.form={roleSort:0,status:'0'};
            },
            //编辑操作
            handleEdit(row) {
                if (this.$refs.form != undefined) {
                    this.$refs.form.clearValidate();
                }
                this.title="修改角色信息";
                this.dialogVisible=true;
                this.form =JSON.parse(JSON.stringify(row));
                this.form.roleId=row.roleId;
            },
            //删除操作
            handleDelete(row) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.delete("system/api/role/delRole/"+row.roleId).then(r=>{
                        if (r.data.t){
                            this.$message.success(r.data.msg);
                        }else {
                            this.$message.error("删除失败");
                        }
                        this.initRoleTable();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //分配权限
            permanage(row){
                //显示树形菜单的弹出层
                this.roleId = row.roleId;
                this.selectMenuOpen = true;
                //获取所有的树形菜单
                this.$axios.get("/system/api/menu/list").then(result => {
                    this.menuOptions = result.data.t;
                })
                //获取当前角色具有的菜单
                this.$axios.get("system/api/menu/findByRoleId/" + this.roleId).then(r => {
                    this.checkIds = r.data.t;
                    //默认选中的树的数据
                    setTimeout(() => {
                        r.data.t.forEach(value => {
                            this.$refs.menu.setChecked(value, true, false);
                        })
                    }, 100)
                })
            }
        },
        created() {
            //加载系统状态
            this.initStatus();
            //初始化role表单
            this.initRoleTable();
        }
    }
</script>
